import { createRoute } from "../createRouterMap";

function runQueue(queue, iterator, cb) {
  function step(index) {
    if (index >= queue.length) return cb();
    let hook = queue[index];
    iterator(hook, () => step(++index))
  }
  step(0);
}

export class Histroy {
  constructor(router) {
    this.router = router;
    this.current = createRoute(null, {path: '/'});
  }
  transitionTo(location, cb) {
    // 获取到最新的路由，根据这个地址渲染组件
    // this.current = {
    //   path: '/home/a',
    //   matched: [{ home的record }, { a的record }]
    // }
    this.current = this.router.match.match(location);

    // 路由守卫
    let queue = [].concat(this.router.beforeHooks);
    const iterator = (hook, next) => {
      // hook(from, to, next);
      hook(this.current, this.router, () => next());
    }
    runQueue(queue, iterator, () => {
      // 渲染对应组件
      this.cb && this.cb(this.current);
      // 回调执行
      cb && cb();
    });
  }
  push(to) {
    // 初始化的时候已经设置了hashchange监听，这里用来触发回调，来修改hash
    this.transitionTo(to, () => {
      window.location.hash = to;
    });
  }
  // 设置了一个改变路由信息的方法，相当于先订阅
  listen(cb) {
    this.cb = cb;
  }
}